package xxx.example.ht.xiti;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Path;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import xxx.example.ht.MyApp;
import xxx.example.ht.R;
import xxx.example.ht.activity.MainActivity;


public class LoginActivity extends AppCompatActivity {

    private AppCompatEditText usernameEditText;
    private AppCompatEditText passwordEditText;
    private AppCompatButton loginButton;
    private AppCompatButton cameraButton;
    private AppCompatImageView mainImageView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        usernameEditText = findViewById(R.id.usernameEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        loginButton = findViewById(R.id.loginButton);
        cameraButton = findViewById(R.id.cameraButton);
        mainImageView=findViewById(R.id.mainImageView);
        camera1Button = findViewById(R.id.camera1Button);
        cropButton = findViewById(R.id.cropButton);
        mainVideoView = findViewById(R.id.mainVideoView);

        ArrayList<String> files = getFilesAllName("/storage/emulated/0/Movies");
        for (int i = 0; i < files.size(); i++){
            if (files.get(i).contains(".mp4")){
                File file = new File(files.get(i));
                mainImageView.setVideoURI(Uri.fromFile(file));
                mainImageView.start();
                break;
            }
        }

        String key = MyApp.get().getSharedPreferences().getString("key", "");
        if (!key.isEmpty()) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        loginButton.setOnClickListener(view -> {
            String mobile = usernameEditText.getText().toString();
            String password = passwordEditText.getText().toString();
            if (mobile.isEmpty()) {
                Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!isMobileNO(mobile)) {
                Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.isEmpty()) {
                Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.length() < 6) {
                Toast.makeText(this, "请输入有效的密码", Toast.LENGTH_SHORT).show();
                return;
            }
            OkGo.<String>post("https://demo.shopwt.com/api/mobile/index.php?w=login")
                    .params("username", mobile)
                    .params("password", password)
                    .params("client", "wap")
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body().toString());
                                if (jsonObject.getInt("code") == 400) {
                                    jsonObject = jsonObject.getJSONObject("datas");
                                    Toast.makeText(LoginActivity.this, jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                jsonObject = jsonObject.getJSONObject("datas");
                                String key = jsonObject.getString("key");
                                MyApp.get().getEditor().putString("key", key).apply();
                                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        });

        cameraButton.setOnClickListener(view -> {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 999);
        });

    }

    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();
    }

    @Override
    public void onResume() {
        super.onResume();
        XXPermissions.with(this).permission(getPermissions1()).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {

            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                Log.d("TAGS", "123");
            }
        });
    }

    private String[] getPermissions1() {

        return new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
        };

    }

    private ArrayList<String> getFilesAllName(String path){
        File file = new File(Path);
        File[] files = file.listFiles();
        if (files == null) {
            return null;
        }
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < file.length; i++) {
        }
        return list;

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 999) {
                Bitmap bitmap = data.getExtras().getParcelable("data");
                mainImageView.setImageBitmap(bitmap);
            }
        }
    }
}
